﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using com.tdb.posion.protocol.protobuf;
using Google.ProtocolBuffers;
using UnityEngine;

public class NetUtil
{
    /// <summary>
    ///     4位字节数组转换为整型
    /// </summary>
    /// <param name="b"></param>
    /// <returns></returns>
    public static int Byte2Int(byte[] b)
    {
        var intValue = 0;
        for (var i = 0; i < b.Length; i++) intValue += (b[i] & 0xFF) << (8 * (3 - i));
        return intValue;
    }

    /// <summary>
    ///     整型转换为4位字节数组
    /// </summary>
    /// <param name="intValue"></param>
    /// <returns></returns>
    public static byte[] Int2Byte(int intValue)
    {
        var b = new byte[4];
        for (var i = 0; i < 4; i++) b[i] = (byte) ((intValue >> (8 * (3 - i))) & 0xFF);
        return b;
    }

    /// <summary>
    ///     根据定长读取消息
    /// </summary>
    /// <param name="byteData"></param>
    /// <returns></returns>
    public static byte[] ReadMsgWithFixedLength(byte[] byteData)
    {
        var lengthBytes = new byte[4];
        Buffer.BlockCopy(byteData, 0, lengthBytes, 0, 4);
        var length = Byte2Int(lengthBytes);
        var packcetData = new byte[length];
        Buffer.BlockCopy(byteData, 4, packcetData, 0, length);
        return packcetData;
    }

    /// <summary>
    ///     获取本地IP
    /// </summary>
    /// <returns></returns>
    public static string GetLocalIp()
    {
        var adrs = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
        foreach (var adr in adrs)
            if (adr.AddressFamily == AddressFamily.InterNetwork)
                return adr.ToString();
        Debug.LogError("Can`not Find LocalIp!");
        return string.Empty;
    }

    public static byte[] ConvertMessage2ByteArray(Message msg)
    {
        byte[] orginData;
        using (var ms = new MemoryStream())
        {
            msg.WriteTo(ms);
            orginData = ms.ToArray();
        }

        return AddBytesLengthHeader(orginData);
    }

    /// <summary>
    ///     服务器传回的protobuf byte[] 转换成Message对象
    /// </summary>
    /// <returns></returns>
    public static Message ByteArray2Message(byte[] protoBufBytes)
    {
        var registry = ExtensionRegistry.CreateInstance();
        PBData.RegisterAllExtensions(registry);
        PBMessage.RegisterAllExtensions(registry);
        var returnMessage = Message.CreateBuilder().MergeFrom(protoBufBytes, registry).Build();
        return returnMessage;
    }

    public static Message CreateMessage<TExtension>(Cmds cmd, GeneratedExtensionLite<Message, TExtension> extension,
        TExtension value)
    {
        var messageBuilder = Message.CreateBuilder();
        messageBuilder.SetCmds(cmd);
        messageBuilder.SetExtension(extension, value);
        return messageBuilder.Build();
    }

    public static byte[] AddBytesLengthHeader(byte[] data)
    {
        var result = new byte[Const.LengthInfoByteCount + data.Length];
        Buffer.BlockCopy(Int2Byte(data.Length), 0, result, 0, Const.LengthInfoByteCount);
        Buffer.BlockCopy(data, 0, result, Const.LengthInfoByteCount, data.Length);
        return result;
    }
}